package com.young.auth.controller;

import com.alibaba.fastjson2.JSONObject;
import com.young.auth.client.ManagerClient;
import com.young.common.execption.ServiceException;
import com.young.common.interf.IBaseController;
import com.young.common.model.ResultData;
import com.young.common.utils.JJwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@RequestMapping("subscriber")
@RestController
public class LoginController implements IBaseController {

    private final ManagerClient managerClient;

    @PostMapping("login")
    ResultData<?> login(@RequestParam String account, @RequestParam String password, @RequestParam Integer type) {
        Object ret = managerClient.tokenUser(account, password, type);
        JSONObject retJson = JSONObject.from(ret);
        JSONObject data = retJson.getJSONObject("data");
        if (null == data) throw new ServiceException("账号或密码错误！");
        if (data.containsKey("status") && 1 != data.getInteger("status")) throw new ServiceException("账号未激活或已注销！");
        JSONObject resp = new JSONObject();
        Long subject = data.getLong("id");
        Map<String, Object> details = new HashMap<>();
        details.put("userId", subject);
        details.put("name", data.getString("name"));
        details.put("phone", data.getString("phone"));
        details.put("superUser", data.getInteger("superUser"));
        String token = JJwtUtils.generateJWTToken(String.valueOf(subject), details, 12);
        resp.put("token", token);
        resp.put("userDetails", details);
        return success(resp);
    }

}
